#include<Eigen/Dense>
#include<vector>
#include<fstream>

Eigen::VectorXd leastSquares(const std::string& filename, int funcType)
{
    std::vector<double>x, y;
    std::ifstream inFile(filename);//打开之前已经导入数据的文件
    double tempX, tempY;

    while (inFile >> tempX >> tempY)
    {
        x.push_back(tempX);//读入x和y；
        y.push_back(tempY);
    }
    Eigen::MatrixXd A(x.size(), funcType + 1);
    Eigen::VectorXd b(x.size()), coeffs(funcType + 1);//定义所求系数向量
    //下面就是最小二乘法的具体实施步骤
    for (size_t i = 0; i < x.size(); ++i)
    {
        A(i, 0) = pow(x[i], funcType);//将多项式写成向量乘积的形式
        for (int j = 1; j <= funcType; j++)
            A(i, j) = pow(x[i], funcType - j);
        b(i) = y[i];
    }
    coeffs = A.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(b);//使用雅可比方法求向量coeff的值
    return coeffs;
}